package org.mqlink4sap.globals;

import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;

import org.mqlink4sap.configuration.LinkDefinition;
import org.mqlink4sap.connectors.IConnector;
import org.mqlink4sap.connectors.MQConnector;
import org.mqlink4sap.connectors.SAPConnector;
import org.mqlink4sap.exceptions.ConnectorException;
import org.mqlink4sap.exceptions.ConnectorInitializationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Worker implements Runnable {

	private static volatile boolean stopFlag = false;

	private IConnector src;
	private IConnector dst;

	private static Logger log = LoggerFactory.getLogger(Worker.class);
	private static ResourceBundle rb = ResourceBundle
			.getBundle("org.mqlink4sap.i18n.text");

	public Worker(IConnector systemA, IConnector systemB) {
		src = systemA;
		dst = systemB;
	}

	@Override
	public void run() {
		try {
			while (!Thread.currentThread().isInterrupted() && stopFlag == false)
				transferMessage();

		} catch (ConnectorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	void transferMessage() throws ConnectorException {
		String id;
		if ((id = src.nextId()) != null)
			if (dst.put(src.get(id)))
				src.remove(id);
	}

	public static Runnable getWorker(LinkDefinition linkDefinition,
			Map<String, Properties> systemsProperties)
			throws ConnectorInitializationException {

		IConnector from = getConnector(IConnector.Direction.Outgoing,
				systemsProperties.get(linkDefinition.From));
		if (from == null) {
			log.error(rb.getString("SystemConnectorInitializationError"),
					linkDefinition.From);
			throw new ConnectorInitializationException();
		}

		IConnector to = getConnector(IConnector.Direction.Incoming,
				systemsProperties.get(linkDefinition.From));
		if (to == null) {
			log.error(rb.getString("SystemConnectorInitializationError"),
					linkDefinition.To);
			throw new ConnectorInitializationException();
		}

		return new Worker(from, to);

	}

	private static IConnector getConnector(IConnector.Direction direction,
			Properties properties) throws ConnectorInitializationException {
		switch (properties.getProperty("Type")) {
		case "SAP":
			return new SAPConnector().initialize(direction, properties);
		case "MQ":
			return new MQConnector().initialize(direction, properties);
		default:
			log.error("SystemConnectorUnknown");
			return null;
		}
	}

}
